package com.ccb.hfms.builder.controller;

import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSONObject;
import com.ccb.hfms.builder.service.IMongoCRUD;

@Controller
@RequestMapping(value = "/")
public class IndexController {
	 @Autowired
	    private IMongoCRUD crud;
	 /**
     *  获取列表
     *    处理 "/" 的 GET 请求，用来获取列表
     *    通过 @RequestParam 传递参数，进一步实现条件查询或者分页查询
     */
    @RequestMapping(method = RequestMethod.GET)
    public String getFormList(ModelMap map) {
    	List<JSONObject> list = crud.findAll("display", "form");    	
    	int i = 1;
    	Iterator<JSONObject> it = list.iterator();
    	while(it.hasNext()) {
    		it.next().put("rowid", i++);
    	}
        map.addAttribute("formList", list);
        return "formList";
    }
    
    /**
     * 显示创建表单
     *
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String createForm(ModelMap map) {
    	UUID id = UUID.randomUUID();
        map.addAttribute("id", id.toString());
        map.addAttribute("action", "create");
        return "builder";
    }
    
    /**
     * 显示创建表单
     *
     */
    @RequestMapping(value = "/view/{id}", method = RequestMethod.GET)
    public String viewForm(@PathVariable String id, ModelMap map) {
    	JSONObject json = crud.findOne(id);
        map.addAttribute("form", json);
        return "view";
    }
    
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public String deteleForm(@PathVariable String id, ModelMap map) {
    	if("null".equals(id)) {
    		crud.remove("id", null);
    	}
    	crud.remove(id);
        return "redirect:/";
    }
    
    @RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
    public String updateForm(@PathVariable String id, ModelMap map) {
    	JSONObject json = crud.findOne(id);
        map.addAttribute("formdata", json);
        map.addAttribute("id", id.toString());
        map.addAttribute("action", "update");
        return "builder";
    }
}
